
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,element = layui.element,form = layui.form,$ = layui.jquery,
    laydate = layui.laydate;

layui.use(['tableEdit',"excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    element.on('nav(librarysavenav)', function (elem) {
        if (elem.text() == "统计") parent.intab("views/jsp/WarehouseManagement/tpl/statistics.jsp", "库存统计");
        else if (elem.text() == "库存账龄") parent.intab("views/jsp/WarehouseManagement/tpl/inventoryaging.jsp", "库存账龄");
        else if (elem.text() == "产品查询") parent.intab("views/jsp/WarehouseManagement/tpl/productquery.jsp", "产品查询");
        else if (elem.text() == "海外仓库租金费设置") parent.intab("views/jsp/WarehouseManagement/overseasWarehouseRentalFee.jsp", "海外仓库租金费设置");
        return false;
    });

    let warehouseCode = [];

    function getxmselect(el, name, data) {
        return warehouseCode = xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            toolbar: {
                show: true,
                list: ['ALL', 'CLEAR']
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }


    layer.ready(function () {
        //获取仓库信息
        $.ajax({
            url: "transfer/getWarehouse",
            success: function (data) {
                if (data.status == 200) {
                    let warehouse = [];
                    for (let i in data.data) {
                        let tmp = {
                            name: data.data[i].name,
                            value: data.data[i].code
                        }
                        warehouse.push(tmp);
                    }
                    getxmselect("#warehouseCode", "warehouseCode", warehouse);
                    form.render('select');
                }
            }
        });

        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        $("#salesmanCode").append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });
    });

//获取当前用户是否有对应权限
//对应角色：管理员(白)，营销总监，海外仓操作，物流主管，物流单证操作，财务 这几个角色可以看到 供应商名称、成本金额小计、成本单价、分摊费用单价
    function getRoles() {
        let allRole = JSON.parse(window.sessionStorage.getItem("AllRole"));
        if (!isEmpty(allRole) && allRole.length > 0) {
            for (let i in allRole) {
                if (!isEmpty(allRole[i]) && !isEmpty(allRole[i]["code"])) {
                    let role = allRole[i]["code"];
                    let flag = role === "admin"
                        || role === "YXZJ003"
                        || role === "HWC007"
                        || role === "WLZG008"
                        || role === "DZCZ006"
                        || role === "CW01"
                    if (flag) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    table.render({
        elem: '#librarysave',
        url: 'stock/listByPage',
        toolbar: '#librarysavetoolbar',
        totalRow: true,
        cols: [[
            {field: 'numbers', width: 50, type: 'numbers', title: '序号', totalRowText: '合计'},
            {field: 'productCode', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'lotNo', width: 120, title: '批次号', sort: true},
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', sort: true},
            {field: 'warehouseName', width: 120, title: '仓库名称', sort: true},
            {field: 'contractNo', width: 120, title: '合同号', sort: true},
            {field: 'contractType', width: 120, title: '合同类型', sort: true},
            {field: 'realQuantity', width: 120, title: '实际数量', sort: true, totalRow: true},
            {field: 'realAvailableQuantity', width: 160, title: '实际可用数量', sort: true, totalRow: true},
            {field: 'canApplyQuantity', width: 140, title: '可申请数量', sort: true, totalRow: true},
            {field: 'outWarehouseApply', width: 160, title: '出库申请数量', sort: true, totalRow: true},
            {field: 'supplierName', width: 140, title: '供应商名称', sort: true},
            {field: 'clientProductNo', width: 120, title: '客户货号', sort: true},
            {field: 'productUnit', width: 120, title: '产品单位', sort: true},
            {field: 'productCname', width: 160, title: '产品中文名称', sort: true},
            {field: 'productEname', width: 160, title: '产品英文名称', sort: true},
            {field: 'productCdesc', width: 160, title: '产品中文描述', sort: true},
            {field: 'productEdesc', width: 160, title: '产品英文描述', sort: true},
            {field: 'color', width: 120, title: '颜色', sort: true},
            {field: 'salesman', width: 120, title: '业务员', sort: true},
            {field: 'salesmanCode', width: 120, title: '业务员编码', sort: true},
            {field: 'costAmount', width: 120, title: '成本金额小计', sort: true, totalRow: true},
            {field: 'productUnitPrice', width: 120, title: '成本单价', sort: true},
            {field: 'memo', title: '备注', width: 80, sort: true},
            {field: 'createDate', width: 120, title: '创建日期', sort: true},
            {field: 'inStoreDate', width: 120, title: '入库日期', sort: true},
            {field: 'shareCostPrice', width: 160, title: '分摊费用单价', sort: true},
            {field: 'purchaseNo', width: 120, title: '采购单号',event: "purchaseNo", sort: true},
            {field: 'inStoreBillNo', width: 120, title: '入库单号', sort: true},
            {field: 'trayNumber', width: 120, title: '托盘入数', sort: true},
            {field: 'totalTray', width: 120, title: '总托盘', sort: true},
            {field: 'productType', width: 120, title: '产品类型', sort: true},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#librarysaveeditor'}
        ]]
        , id: 'librarysavetableid'
        , height: $(document).height() - $('#librarysave').offset().top - 50
        , page: true
        , limit: 100
        , limits: [100, 300, 500, 1000],
        done: function (res, curr, count) {
            hoverOpenImg();//显示大图
            //字段权限控制
            if (!getRoles()) {
                $("[data-field='supplierName']").css('display', 'none');
                $("[data-field='costAmount']").css('display', 'none');
                $("[data-field='productUnitPrice']").css('display', 'none');
                $("[data-field='shareCostPrice']").css('display', 'none');
            }
            form.render('select');
        }
    });
    table.on('tool(librarysavetable)', function (obj) {
        if (obj.event === 'selectdetail') {
            parent.intab("views/jsp/WarehouseManagement/tpl/librarysavedetail.jsp?id=" + obj.data.id, "查看明细")
        }else if (obj.event === "purchaseNo"){
            let purchaseNo = obj.data.purchaseNo;
            if(!isEmpty(purchaseNo)){
                let res = getPurchaseInfoByNo(purchaseNo);
                parent.intab("views/jsp/ExportBusiness/tpl/viewprocurement.jsp?id="+res.id+"&types="+res.purchaseType,"采购明细")
            }
        }
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    //通过采购单号获取采购信息
    function getPurchaseInfoByNo(purchaseNo){
        let res = [];
        $.ajax({
            url: 'purchase/getPurchaseInfo',
            data:{
                purchaseNo:purchaseNo
            },
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    res = data.data;
                }
            }
        });
        return res;
    }

//监听显示零库存
    form.on('checkbox(zeroStockCol)', function (data) {
        //如果选中,则显示零库存
        if (data.elem.checked) {
            $("#zeroStock").val(1);
        } else {
            $("#zeroStock").val(0);
        }
    });
//监听隐藏停用仓库
    form.on('checkbox(hideStopUseStockCol)', function (data) {
        //如果选中,则显停用仓库
        if (data.elem.checked) {
            $("#hideStopUseStock").val(1);
        } else {
            $("#hideStopUseStock").val(0);
        }
    });
    form.on('submit(submitform)', function (data) {
        table.reload('librarysavetableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: data.field
        }, 'data');

        return false;
    });

    document.getElementById('clear').onclick = function () {
        warehouseCode.setValue([])
    };

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        //字段权限
        let flag = getRoles();
        let queryReqData = queryReq.field;
        queryReqData["show"] = flag;
        $.ajax({
            data: queryReqData,
            url: "stock/export/stockExport",
            success: function (res) {
                if (res.status == 200) {
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '库存.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });

});

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
